import os
import pandas as pd

# 定义路径
base_path = "seedwords_agencywords/agency_words"  # 假设文件夹结构保持不变

# 获取所有种子关键词的文件列表
seedwords_files = [f for f in os.listdir(base_path) if f.startswith("seedword_") and f.endswith(".txt")]

# 初始化存储竞争关键词的字典
competing_keywords = {}

# 第一步：读取每个种子关键词的文件并提取前5个竞争关键词
for seed_file in seedwords_files:
    seed_name = seed_file.replace("seedword_", "").replace(".txt", "")  # 提取种子关键词名称
    file_path = os.path.join(base_path, seed_file)

    # 读取文件内容并提取前5个中介关键词
    with open(file_path, 'r', encoding='utf-8') as f:
        keywords = []
        for line in f:
            if "中介关键字：" in line:
                keyword = line.split("中介关键字：")[1].split("||")[0].strip()  # 提取中介关键词部分
                keywords.append(keyword)
            if len(keywords) >= 5:
                break  # 只提取前5个关键词
        competing_keywords[seed_name] = keywords

# 第二步：定义Compkey算法计算竞争程度
def calculate_competition_degree(comp_keywords):
    import random  # 这里保持使用随机数模拟的方式

    competition_scores = {}

    for keyword in comp_keywords:
        search_volume = random.randint(1000, 100000)  # 模拟搜索量
        ad_competition = random.uniform(0.1, 1.0)  # 模拟广告竞争程度（0-1尺度）
        relevance_score = random.uniform(0.1, 1.0)  # 模拟相关性（0-1尺度）

        # Compkey公式（示例：search_volume * ad_competition * relevance_score）
        competition_degree = search_volume * ad_competition * relevance_score
        competition_scores[keyword] = competition_degree

    return competition_scores

# 第三步：计算所有竞争关键词的竞争程度
all_competition_scores = []

for seed, comp_keywords in competing_keywords.items():
    scores = calculate_competition_degree(comp_keywords)
    for keyword, competition_degree in scores.items():
        all_competition_scores.append({
            '种子关键词': seed,
            '竞争关键词': keyword,
            '竞争程度': competition_degree
        })

# 第四步：将所有结果存储在一个DataFrame中并排序
all_results_df = pd.DataFrame(all_competition_scores)
all_results_df = all_results_df.sort_values(by=['种子关键词', '竞争程度'], ascending=[True, False]).reset_index(drop=True)

# 第五步：将结果保存为简洁格式的CSV文件
all_results_df[['种子关键词', '竞争关键词', '竞争程度']].to_csv("competition_results.csv", index=False, encoding='utf-8-sig')
print("所有竞争结果已计算并存入'competition_results.csv'。")

# import random
# import pandas as pd
# import numpy as np
#
# # 第一步：为每个种子词生成随机的竞争关键词
# seedwords_list = ['图片', '手机', '意思', '小说', '视频', '下载', '大全', '电影', '中国', '世界', '重生', '百度', '官网', '英语', '电视剧']
# competing_keywords = {}
#
# for seed in seedwords_list:
#     competing_keywords[seed] = [f"{seed}_竞争{random.randint(1, 100)}" for _ in range(5)]
#
# # 第二步：定义Compkey算法计算竞争程度
# def calculate_competition_degree(comp_keywords):
#     competition_scores = {}
#
#     for keyword in comp_keywords:
#         search_volume = random.randint(1000, 100000)  # 模拟搜索量
#         ad_competition = random.uniform(0.1, 1.0)  # 模拟广告竞争程度（0-1尺度）
#         relevance_score = random.uniform(0.1, 1.0)  # 模拟相关性（0-1尺度）
#
#         # Compkey公式（示例：search_volume * ad_competition * relevance_score）
#         competition_degree = search_volume * ad_competition * relevance_score
#         competition_scores[keyword] = competition_degree
#
#     return competition_scores
#
# # 第三步：计算所有竞争关键词的竞争程度
# all_competition_scores = []
#
# for seed, comp_keywords in competing_keywords.items():
#     scores = calculate_competition_degree(comp_keywords)
#     for keyword, competition_degree in scores.items():
#         all_competition_scores.append({
#             '种子关键词': seed,
#             '竞争关键词': keyword,
#             '竞争程度': competition_degree
#         })
#
# # 第四步：将所有结果存储在一个DataFrame中并排序
# all_results_df = pd.DataFrame(all_competition_scores)
# all_results_df = all_results_df.sort_values(by=['种子关键词', '竞争程度'], ascending=[True, False]).reset_index(drop=True)
#
# # 第五步：将合并结果保存到CSV文件中
# all_results_df.to_csv("competition_results.csv", index=False, encoding='utf-8-sig')
# print("所有竞争结果已计算并存入'competition_results.csv'。")
